package com.freeman.cement.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freeman.cement.entity.*;
import com.freeman.cement.entity.hikvision.HikResultObject;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.mapper.CameraDao;
import com.freeman.cement.mapper.DeptDao;
import com.freeman.cement.myenum.Enabled;
import com.freeman.cement.util.StringUtils;
import com.freeman.cement.util.hikiscUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/region")
@CrossOrigin    //允许跨域访问
public class RegionController {

    @Resource
    private CameraDao cameraDao;
    @Resource
    private DeptDao deptDao;

    /**
     * 获取区域树结构，只支持最高三级区域结构 “硬盘录像机”-生产监控-“”--“内10.35.70.1”
     * @return
     */
    @RequestMapping(value = "/getRegionTree", method = RequestMethod.POST)
    public ResponseResult getRegionTree() {
        // 从海康平台获取区域列表的接口
        // http://10.35.0.76:8182/sysmanage/hikisc/transport/api/resource/v1/regions?pageNo=1&pageSize=1000
        String result = hikiscUtil.getRegionList(1, 1000);
        HikResultObject ro = JSONObject.parseObject(result, HikResultObject.class);
        if (ro.getCode().equals("0")) {
            JSONObject data = JSONObject.parseObject(ro.getData());
            Integer total = data.getInteger("total");
            JSONArray list = data.getJSONArray("list");
            List<Region> regions = list.toJavaList(Region.class);
            //！！！只支持最高三级区域结构 ！！！
            if (regions != null && regions.size() > 0) {
                Optional<Region> first = regions.stream().filter(s -> s.getParentIndexCode().equals("-1")).findFirst();
                if (first.isPresent()) {
                    //根节点/第一级节点
                    Region root = first.get();
                    RegionNode rootNode = new RegionNode(root.getName(), root.getIndexCode(), new ArrayList<RegionNode>());
                    //第二级节点
                    List<Region> nood0 = regions.stream().filter(s -> s.getParentIndexCode().equals(root.getIndexCode())).collect(Collectors.toList());
                    nood0.forEach(s -> {
                        rootNode.getChildren().add(new RegionNode(s.getName(), s.getIndexCode(), new ArrayList<RegionNode>()));
                    });
                    //第三级节点
                    rootNode.getChildren().forEach(s -> {
                        List<Region> nood1 = regions.stream().filter(p -> p.getParentIndexCode().equals(s.getRegionIndexCode())).collect(Collectors.toList());
                        nood1.forEach(v -> {
                            s.getChildren().add(new RegionNode(v.getName(), v.getIndexCode(), null));
                        });
                    });
                    return ResponseResult.success(rootNode);
                }
            }
            return ResponseResult.success(null);
        } else {
            throw new AppException(56090, "解析区域列表错误，错误码" + ro.getCode());
        }
    }

    /**
     * 根据用户权限过滤摄像头列表
     * @param cameras 原始摄像头列表
     * @return 过滤后的摄像头列表
     */
    private List<Camera> filterCamerasByPermission(List<Camera> cameras) {
        if (cameras == null || cameras.isEmpty()) {
            return cameras;
        }
        
        // 获取当前用户角色和用户ID
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return cameras;
        }
        
        HttpServletRequest request = attributes.getRequest();
        String userRole = (String) request.getAttribute("userRole");
        
        // 如果是管理员，返回所有摄像头
        if ("管理员".equals(userRole)) {
            return cameras;
        }
        
        // 非管理员，只返回关联值班室的摄像头
        Integer userId = (Integer) request.getAttribute("userId");
        if (userId == null) {
            return new ArrayList<>();
        }
        
        Dept userDept = deptDao.selectDutyRoomByid(userId);
        if (userDept == null) {
            return new ArrayList<>();
        }
        
        // 获取用户值班室的所有摄像头列表
        Camera cameraFilter = new Camera();
        cameraFilter.setDeptDutyId(userDept.getId());
        cameraFilter.setIsEnabled(Enabled.TRUE.getIndex());
        List<Camera> userCameras = cameraDao.selectCamera(cameraFilter);
        if (userCameras == null) {
            return new ArrayList<>();
        }
        
        // 过滤出用户值班室的摄像头索引编码
        List<String> userCameraIndexCodes = userCameras.stream()
                .filter(c -> c.getCameraIndexCode() != null)
                .map(Camera::getCameraIndexCode)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        
        // 只返回用户有权限的摄像头
        return cameras.stream()
                .filter(c -> c.getCameraIndexCode() != null && 
                           userCameraIndexCodes.contains(c.getCameraIndexCode()))
                .collect(Collectors.toList());
    }

    /**
     * 获取区域和摄像头组成的树结构
     * 这个接口区域信息是从海康平台读出来的，区域下的摄像头列表也是从海康平台中读出来的
     * 添加了权限控制：管理员可以看到所有摄像头，普通用户只能看到自己值班室的摄像头
     * @return
     */
    @RequestMapping(value = "/getRegionCameraTree", method = RequestMethod.POST)
    public ResponseResult getRegionCameraTree() {
        // 从海康平台获取区域列表的接口
        // http://10.35.0.76:8182/sysmanage/hikisc/transport/api/resource/v1/regions?pageNo=1&pageSize=1000
        //String result = "{\"code\":\"0\",\"msg\":\"success\",\"data\":{\"total\":19,\"pageNo\":1,\"pageSize\":1000,\"list\":[{\"indexCode\":\"root000000\",\"name\":\"硬盘录像机\",\"parentIndexCode\":\"-1\",\"treeCode\":\"0\"},{\"indexCode\":\"d05477fe-46d4-47a1-8706-e903a81c9021\",\"name\":\"内192.168.10.70外10.35.70.7\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"a83964e9-74a8-44d1-9615-0dc9937d82dd\",\"name\":\"通用行为分析\",\"parentIndexCode\":\"fbfcc135-eb77-487c-a952-679437980f7e\",\"treeCode\":\"0\"},{\"indexCode\":\"4b45f983-acf6-4085-b254-4000dfae8706\",\"name\":\"192.168.10.198\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"6ea3fec7-f8a7-4195-8a61-0a5e49b26b09\",\"name\":\"卡口终端\",\"parentIndexCode\":\"fbfcc135-eb77-487c-a952-679437980f7e\",\"treeCode\":\"0\"},{\"indexCode\":\"a35da64c-4412-4b2a-a23c-8ead930dc426\",\"name\":\"192.168.10.201外10.35.70.13\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"7e56e9df-5a53-4df3-9f71-185b77508588\",\"name\":\"AI行为超脑\",\"parentIndexCode\":\"fbfcc135-eb77-487c-a952-679437980f7e\",\"treeCode\":\"0\"},{\"indexCode\":\"649cbd49-f8c3-45be-b827-aca3c30ce0a9\",\"name\":\"内192.168.10.203外10.35.70.14\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"dfc687fc-994a-46dd-bbf8-ea982cf1643e\",\"name\":\"内10.0.32.9外10.35.70.10\",\"parentIndexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"treeCode\":\"0\"},{\"indexCode\":\"3bca2769-5ee4-4f35-b030-346fa6bf0ebb\",\"name\":\"内192.168.10.205外10.35.70.15\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"e797b7f4-65b3-4014-920a-c942f823e672\",\"name\":\"内10.0.32.35外10.35.70.11\",\"parentIndexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"treeCode\":\"0\"},{\"indexCode\":\"d242d53b-2eca-4b2b-a73f-f3bfd6b89246\",\"name\":\"内192.168.10.207外10.35.70.16\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"a0c2804d-2513-43d6-9eb3-507be6bd8a8e\",\"name\":\"192.168.10.253\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"bb3114da-9d08-4d7f-b2d1-d3669f3fc828\",\"name\":\"10.0.32.171发运未设置\",\"parentIndexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"treeCode\":\"0\"},{\"indexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"name\":\"非生产监控\",\"parentIndexCode\":\"root000000\",\"treeCode\":\"0\"},{\"indexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"name\":\"生产监控\",\"parentIndexCode\":\"root000000\",\"treeCode\":\"0\"},{\"indexCode\":\"6e35dbbe-37e7-46e0-8785-c37621c8c0c8\",\"name\":\"内10.0.32.251外10.35.70.9\",\"parentIndexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"treeCode\":\"0\"},{\"indexCode\":\"fbfcc135-eb77-487c-a952-679437980f7e\",\"name\":\"行为分析服务\",\"parentIndexCode\":\"root000000\",\"treeCode\":\"0\"},{\"indexCode\":\"e54e2bf4-910d-470d-a58a-928fa3b49544\",\"name\":\"超脑\",\"parentIndexCode\":\"root000000\",\"treeCode\":\"0\"}]}}";
        //String result = "{\"code\":\"0\",\"msg\":\"success\",\"data\":{\"total\":2,\"pageNo\":1,\"pageSize\":1000,\"list\":[{\"indexCode\":\"502fa74fd39e46f8a1a2ef650a097545\",\"regionIndexCode\":\"root000000\",\"name\":\"卡口北1\",\"parentIndexCode\":\"b66e3fce864b4772865f127b0c18626f\",\"cameraType\":0,\"chanNum\":1,\"dacIndexCode\":\"卡口南1\",\"capability\":\"@event_veh@event_veh_violation@event_veh_recognition@event_veh_direction@event_face@vss@net@maintenance@event_veh_traffic@event_device@status@\",\"channelType\":\"analog\",\"decodeTag\":\"hikvision\",\"comId\":\"sdmc\",\"resourceType\":\"monitoringPoint,camera\",\"createTime\":\"2023-02-27T14:01:50.040+08:00\",\"updateTime\":\"2023-02-27T14:05:22.257+08:00\",\"sort\":2378,\"disOrder\":2378,\"transType\":1,\"treatyType\":\"hiksdk_net\",\"cascadeType\":0,\"regionName\":\"硬盘录像机\",\"regionPath\":\"@root000000@\",\"regionPathName\":\"硬盘录像机\"},{\"indexCode\":\"353ccf504d394d45962e919cdde94a1a\",\"regionIndexCode\":\"root000000\",\"name\":\"卡口南1\",\"parentIndexCode\":\"1d14b355cb6a4298a1710d5cd1bccb02\",\"cameraType\":0,\"chanNum\":1,\"dacIndexCode\":\"卡口北1\",\"capability\":\"@event_veh@event_veh_violation@event_veh_recognition@event_veh_direction@event_face@vss@net@maintenance@event_veh_traffic@event_device@status@\",\"channelType\":\"analog\",\"decodeTag\":\"hikvision\",\"comId\":\"sdmc\",\"resourceType\":\"monitoringPoint,camera\",\"createTime\":\"2023-02-27T14:02:11.595+08:00\",\"updateTime\":\"2023-02-27T14:05:22.256+08:00\",\"sort\":2377,\"disOrder\":2377,\"transType\":1,\"treatyType\":\"hiksdk_net\",\"cascadeType\":0,\"regionName\":\"硬盘录像机\",\"regionPath\":\"@root000000@\",\"regionPathName\":\"硬盘录像机\"}]}}";
        //String result = "{\"code\":\"0\",\"msg\":\"success\",\"data\":{\"total\":19,\"pageNo\":1,\"pageSize\":1000,\"list\":[{\"indexCode\":\"root000000\",\"name\":\"硬盘录像机\",\"parentIndexCode\":\"-1\",\"treeCode\":\"0\"},{\"indexCode\":\"d05477fe-46d4-47a1-8706-e903a81c9021\",\"name\":\"内192.168.10.70外10.35.70.7\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"a83964e9-74a8-44d1-9615-0dc9937d82dd\",\"name\":\"通用行为分析\",\"parentIndexCode\":\"fbfcc135-eb77-487c-a952-679437980f7e\",\"treeCode\":\"0\"},{\"indexCode\":\"4b45f983-acf6-4085-b254-4000dfae8706\",\"name\":\"192.168.10.198\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"6ea3fec7-f8a7-4195-8a61-0a5e49b26b09\",\"name\":\"卡口终端\",\"parentIndexCode\":\"fbfcc135-eb77-487c-a952-679437980f7e\",\"treeCode\":\"0\"},{\"indexCode\":\"a35da64c-4412-4b2a-a23c-8ead930dc426\",\"name\":\"192.168.10.201外10.35.70.13\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"7e56e9df-5a53-4df3-9f71-185b77508588\",\"name\":\"AI行为超脑\",\"parentIndexCode\":\"fbfcc135-eb77-487c-a952-679437980f7e\",\"treeCode\":\"0\"},{\"indexCode\":\"649cbd49-f8c3-45be-b827-aca3c30ce0a9\",\"name\":\"内192.168.10.203外10.35.70.14\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"dfc687fc-994a-46dd-bbf8-ea982cf1643e\",\"name\":\"内10.0.32.9外10.35.70.10\",\"parentIndexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"treeCode\":\"0\"},{\"indexCode\":\"3bca2769-5ee4-4f35-b030-346fa6bf0ebb\",\"name\":\"内192.168.10.205外10.35.70.15\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"e797b7f4-65b3-4014-920a-c942f823e672\",\"name\":\"内10.0.32.35外10.35.70.11\",\"parentIndexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"treeCode\":\"0\"},{\"indexCode\":\"d242d53b-2eca-4b2b-a73f-f3bfd6b89246\",\"name\":\"内192.168.10.207外10.35.70.16\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"a0c2804d-2513-43d6-9eb3-507be6bd8a8e\",\"name\":\"192.168.10.253\",\"parentIndexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"treeCode\":\"0\"},{\"indexCode\":\"bb3114da-9d08-4d7f-b2d1-d3669f3fc828\",\"name\":\"10.0.32.171发运未设置\",\"parentIndexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"treeCode\":\"0\"},{\"indexCode\":\"a83140cc-838e-40dd-b180-6b626a653a43\",\"name\":\"非生产监控\",\"parentIndexCode\":\"root000000\",\"treeCode\":\"0\"},{\"indexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"name\":\"生产监控\",\"parentIndexCode\":\"root000000\",\"treeCode\":\"0\"},{\"indexCode\":\"6e35dbbe-37e7-46e0-8785-c37621c8c0c8\",\"name\":\"内10.0.32.251外10.35.70.9\",\"parentIndexCode\":\"634624f5-223a-4677-abd5-ac41b742a8fb\",\"treeCode\":\"0\"},{\"indexCode\":\"fbfcc135-eb77-487c-a952-679437980f7e\",\"name\":\"行为分析服务\",\"parentIndexCode\":\"root000000\",\"treeCode\":\"0\"},{\"indexCode\":\"e54e2bf4-910d-470d-a58a-928fa3b49544\",\"name\":\"超脑\",\"parentIndexCode\":\"root000000\",\"treeCode\":\"0\"}]}}";

        String result = hikiscUtil.getRegionList(1, 1000);
        HikResultObject ro = JSONObject.parseObject(result, HikResultObject.class);
        if (ro.getCode().equals("0")) {
            JSONObject data = JSONObject.parseObject(ro.getData());
            Integer total = data.getInteger("total");
            JSONArray list = data.getJSONArray("list");
            List<Region> regions = list.toJavaList(Region.class);
            if (regions != null && regions.size() > 0) {
                Optional<Region> first = regions.stream().filter(s -> s.getParentIndexCode().equals("-1")).findFirst();
                if (first.isPresent()) {
                    //根节点/第一级节点
                    Region root = first.get();
                    TreeNode rootNode = new TreeNode(root.getName(), root.getIndexCode(), new ArrayList<TreeNode>());
                    //一级节点挂载摄像头
                    if(rootNode != null && rootNode.getIndexCode() != null) {
                        List<Camera> cameras0 = hikiscUtil.selectCameraByRegionIndexCode(rootNode.getIndexCode());
                        // 应用权限过滤
                        cameras0 = filterCamerasByPermission(cameras0);
                        try {
                            if (cameras0 != null && cameras0.size() > 0) {
                                cameras0.forEach(c -> {
                                    if (c != null && c.getCameraName() != null && StringUtils.isNotBlank(c.getCameraName()) && c.getCameraIndexCode() != null && StringUtils.isNotBlank(c.getCameraIndexCode())) {
                                        //第二级节点/摄像头节点
                                        TreeNode cnode = new TreeNode(c.getCameraName(), c.getCameraIndexCode(), null);
                                        if (cnode != null) {
                                            rootNode.getChildren().add(cnode);
                                            //System.out.println(cnode.getName() + "/" + cnode.getIndexCode());
                                        }
                                    }
                                });
                            }
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                    //第二级节点
                    List<Region> nood0 = regions.stream().filter(s -> s.getParentIndexCode().equals(root.getIndexCode())).collect(Collectors.toList());
                    if(nood0 != null && nood0.size() > 0) {
                        nood0.forEach(s -> {
                            if (s != null && s.getName() != null && s.getIndexCode() != null) {
                                rootNode.getChildren().add(new TreeNode(s.getName(), s.getIndexCode(), new ArrayList<TreeNode>()));
                                //System.out.println(s.getName() + "/" + s.getIndexCode());
                            }
                        });
                    }
                    if(rootNode.getChildren() != null && rootNode.getChildren().size() > 0) {
                        rootNode.getChildren().forEach(s -> {
                            if (s != null && s.getIndexCode() != null) {
                                //二级节点挂载摄像头
                                List<Camera> cameras1 = hikiscUtil.selectCameraByRegionIndexCode(s.getIndexCode());
                                // 应用权限过滤
                                cameras1 = filterCamerasByPermission(cameras1);
                                try {
                                    if (cameras1 != null && cameras1.size() > 0) {
                                        cameras1.forEach(c -> {
                                            if (c != null && c.getCameraName() != null && StringUtils.isNotBlank(c.getCameraName()) && c.getCameraIndexCode() != null && StringUtils.isNotBlank(c.getCameraIndexCode())) {
                                                //第三级节点/摄像头节点
                                                TreeNode cnode = new TreeNode(c.getCameraName(), c.getCameraIndexCode(), null);
                                                if (cnode != null) {
                                                    s.getChildren().add(cnode);
                                                    //System.out.println(s.getName() + "/" + s.getIndexCode());
                                                }
                                            }
                                        });
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            //第三级节点
                            List<Region> nood1 = regions.stream().filter(p -> p.getParentIndexCode().equals(s.getIndexCode())).collect(Collectors.toList());
                            if(nood1 != null && nood1.size() > 0) {
                                nood1.forEach(v -> {
                                    if (v != null && v.getName() != null && v.getIndexCode() != null) {
                                        s.getChildren().add(new TreeNode(v.getName(), v.getIndexCode(), null));
                                        //System.out.println(s.getName() + "/" + s.getIndexCode());
                                    }
                                });
                            }
                            if(s.getChildren() != null && s.getChildren().size() > 0) {
                                //这里的x是三级节点
                                s.getChildren().forEach(x -> {
                                    if (StringUtils.isNotBlank(x.getIndexCode())) {
                                        x.setChildren(new ArrayList<>());
                                        if (x != null && x.getIndexCode() != null) {
                                            List<Camera> cameras2 = hikiscUtil.selectCameraByRegionIndexCode(x.getIndexCode());
                                            // 应用权限过滤
                                            cameras2 = filterCamerasByPermission(cameras2);
                                            try {
                                                if (cameras2 != null && cameras2.size() > 0) {
                                                    cameras2.forEach(c -> {
                                                        if (c != null && c.getCameraName() != null && StringUtils.isNotBlank(c.getCameraName()) && c.getCameraIndexCode() != null && StringUtils.isNotBlank(c.getCameraIndexCode())) {
                                                            //第四级节点/摄像头节点
                                                            TreeNode cnode = new TreeNode(c.getCameraName(), c.getCameraIndexCode(), null);
                                                            if (cnode != null) {
                                                                x.getChildren().add(cnode);
                                                                //System.out.println(cnode.getName() + "/" + cnode.getIndexCode());
                                                            }
                                                        }
                                                    });
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                });
                            }
                        });
                    }
                    return ResponseResult.success(rootNode);
                }
            }
            return ResponseResult.success(null);
        } else {
            throw new AppException(56090, "解析区域列表错误，错误码" + ro.getCode());
        }
    }

    /**
     * 获取区域和摄像头组成的树结构
     * 支持一级、二级、三级下挂载摄像头
     * 这个接口区域信息是从海康平台读出来的，区域下的摄像头列表是从数据库中读出来的
     * 所以如果海康平台修改过摄像头的区域信息后，区域下的摄像头就会不一致
     * @return
     */
    /*
    @RequestMapping(value = "/getRegionCameraTreeFromDataBase", method = RequestMethod.POST)
    public ResponseResult getRegionCameraTreeFromDataBase() {
        // 从海康平台获取区域列表的接口
        // http://10.35.0.76:8182/sysmanage/hikisc/transport/api/resource/v1/regions?pageNo=1&pageSize=1000
        String result = hikiscUtil.getRegionList(1, 1000);
        HikResultObject ro = JSONObject.parseObject(result, HikResultObject.class);
        if (ro.getCode().equals("0")) {
            JSONObject data = JSONObject.parseObject(ro.getData());
            Integer total = data.getInteger("total");
            JSONArray list = data.getJSONArray("list");
            List<Region> regions = list.toJavaList(Region.class);
            if (regions != null && regions.size() > 0) {
                Optional<Region> first = regions.stream().filter(s -> s.getParentIndexCode().equals("-1")).findFirst();
                if (first.isPresent()) {
                    //根节点/第一级节点
                    Region root = first.get();
                    TreeNode rootNode = new TreeNode(root.getName(), root.getIndexCode(), new ArrayList<TreeNode>());
                    //一级节点挂载摄像头
                    if (rootNode != null && rootNode.getIndexCode() != null && StringUtils.isNotBlank(rootNode.getIndexCode())) {
                        List<Camera> cameras0 = cameraDao.findCamera(rootNode.getIndexCode(), Enabled.TRUE.getIndex());
                        if (cameras0 != null && cameras0.size() > 0) {
                            cameras0.forEach(c -> {
                                if (c != null && c.getIsEnabled() != null && c.getIsEnabled() == Enabled.TRUE.getIndex() && c.getCameraIndexCode() != null && StringUtils.isNotBlank(c.getCameraIndexCode())) {
                                    //第二级节点/摄像头节点
                                    TreeNode cnode = new TreeNode(c.getCameraName(), c.getCameraIndexCode(), null);
                                    rootNode.getChildren().add(cnode);
                                }
                            });
                        }
                    }

                    //第二级节点
                    List<Region> nood0 = regions.stream().filter(s -> s.getParentIndexCode().equals(root.getIndexCode())).collect(Collectors.toList());
                    nood0.forEach(s -> {
                        rootNode.getChildren().add(new TreeNode(s.getName(), s.getIndexCode(), new ArrayList<TreeNode>()));
                    });

                    rootNode.getChildren().forEach(s -> {
                        //二级节点挂载摄像头
                        if (s != null && s.getIndexCode() != null && StringUtils.isNotBlank(s.getIndexCode())) {
                            List<Camera> cameras1 = cameraDao.findCamera(s.getIndexCode(), Enabled.TRUE.getIndex());
                            if (cameras1 != null && cameras1.size() > 0) {
                                cameras1.forEach(c -> {
                                    if (c != null && c.getIsEnabled() != null && c.getIsEnabled() == Enabled.TRUE.getIndex() && c.getCameraIndexCode() != null && StringUtils.isNotBlank(c.getCameraIndexCode())) {
                                        //第三级节点/摄像头节点
                                        TreeNode cnode = new TreeNode(c.getCameraName(), c.getCameraIndexCode(), null);
                                        s.getChildren().add(cnode);
                                    }
                                });
                            }
                        }

                        //第三级节点
                        List<Region> nood1 = regions.stream().filter(p -> p.getParentIndexCode().equals(s.getIndexCode())).collect(Collectors.toList());
                        nood1.forEach(v -> {
                            s.getChildren().add(new TreeNode(v.getName(), v.getIndexCode(), null));
                        });
                        //这里的x是三级节点
                        s.getChildren().forEach(x -> {
                            if (x != null && x.getIndexCode() != null && StringUtils.isNotBlank(x.getIndexCode())) {
                                x.setChildren(new ArrayList<>());
                                List<Camera> cameras2 = cameraDao.findCamera(x.getIndexCode(), Enabled.TRUE.getIndex());
                                if (cameras2 != null && cameras2.size() > 0) {
                                    cameras2.forEach(c -> {
                                        if (c != null && c.getIsEnabled() != null && c.getIsEnabled() == Enabled.TRUE.getIndex() && c.getCameraIndexCode() != null && StringUtils.isNotBlank(c.getCameraIndexCode())) {
                                            //第四级节点/摄像头节点
                                            TreeNode cnode = new TreeNode(c.getCameraName(), c.getCameraIndexCode(), null);
                                            x.getChildren().add(cnode);
                                        }
                                    });
                                }
                            }
                        });
                    });
                    return ResponseResult.success(rootNode);
                }
            }
            return ResponseResult.success(null);
        } else {
            throw new AppException(56090, "解析区域列表错误，错误码" + ro.getCode());
        }
    }
    */

    /**
     * 用于模拟海康平台的区域接口
     * 获取区域列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    /*@NeedRole("管理员||值班员")
    @RequestMapping(value = "/regions.do", method = RequestMethod.POST, produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String regions(int pageNo, int pageSize)
    {
        if(pageNo > 0 && pageSize <=1000 )
        {
            Region root = new Region();
            root.setIndexCode("root0");
            root.setName("区域");
            root.setParentIndexCode("null");
            root.setTreeCode("0");

            Region node0 = new Region();
            node0.setIndexCode("node0");
            node0.setName("前厂区");
            node0.setParentIndexCode("root0");
            node0.setTreeCode("0");

//            Region node00 = new Region();
//            node00.setIndexCode("node00");
//            node00.setName("前厂区-501");
//            node00.setParentIndexCode("node0");
//            node00.setTreeCode("0");

            Region leaf0 = new Region();
            leaf0.setIndexCode("183b2031c1db4f368f015fe2562e0010");
            leaf0.setName("500#三层入口处");
            leaf0.setParentIndexCode("node0");
            leaf0.setTreeCode("0");

            Region leaf1 = new Region();
            leaf1.setIndexCode("083b2031c1db4f368f015fe2562e0014");
            leaf1.setName("500#三层出口处");
            leaf1.setParentIndexCode("node0");
            leaf1.setTreeCode("0");

            Region node1 = new Region();
            node1.setIndexCode("node1");
            node1.setName("后厂区");
            node1.setParentIndexCode("root0");
            node1.setTreeCode("0");

//            Region node10 = new Region();
//            node10.setIndexCode("node10");
//            node10.setName("后厂区-500");
//            node10.setParentIndexCode("node1");
//            node10.setTreeCode("0");

            Region leaf2 = new Region();
            leaf2.setIndexCode("083b2031c1db4f368f015fe2562e0012");
            leaf2.setName("501#一层入口处");
            leaf2.setParentIndexCode("node1");
            leaf2.setTreeCode("0");

            Region leaf3 = new Region();
            leaf3.setIndexCode("083b2031c1db4f368f015fe2562e0013");
            leaf3.setName("501#二层入口处");
            leaf3.setParentIndexCode("node1");
            leaf3.setTreeCode("0");

//            Region leaf4 = new Region();
//            leaf3.setIndexCode("083b2031c1db4f368f015fe2562e0014");
//            leaf3.setName("5001#三层出口处");
//            leaf3.setParentIndexCode("node0");
//            leaf3.setTreeCode("0");

            List<Region> list = new ArrayList<>();
            list.add(root);
            list.add(node0);
            list.add(node1);
            list.add(leaf0);
            list.add(leaf1);
            list.add(leaf2);
            list.add(leaf3);
//            list.add(leaf4);

            JSONObject object = new JSONObject();
            JSONObject data = new JSONObject();
            object.put("total", 18);
            object.put("pageNo", pageNo);
            object.put("pageSize", pageSize);
            object.put("list", list);

            object.put("code", "0");
            object.put("msg", "SUCCESS");
            object.put("data", data);

            return JSON.toJSONString(object);
        }
        else
            return "分页请求范围错误";
    }*/

}
